package com.ht.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.constant.CommonConstant;
import com.ht.constant.CommonSendStatus;
import com.ht.modules.system.entity.SysAnnouncement;
import com.ht.modules.system.entity.SysAnnouncementSend;
import com.ht.modules.system.mapper.SysAnnouncementMapper;
import com.ht.modules.system.mapper.SysAnnouncementSendMapper;
import com.ht.modules.system.service.ISysAnnouncementService;
import jakarta.annotation.Resource;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 *  系统通告表
 * @Author: jeecg-boot
 * @Date:  2019-01-02
 * @Version: V1.0
 */
@Service
public class SysAnnouncementServiceImpl extends ServiceImpl<SysAnnouncementMapper, SysAnnouncement> implements ISysAnnouncementService {

	@Resource
	private SysAnnouncementMapper sysAnnouncementMapper;

	@Resource
	private SysAnnouncementSendMapper sysAnnouncementSendMapper;

	@Transactional
	@Override
	public void saveAnnouncement(SysAnnouncement sysAnnouncement) {
		if(sysAnnouncement.getMsgType().equals(CommonConstant.MSG_TYPE_ALL)) {
			sysAnnouncementMapper.insert(sysAnnouncement);
		}else {
			// 1.插入通告表记录
			sysAnnouncementMapper.insert(sysAnnouncement);
			// 2.插入用户通告阅读标记表记录
			String userId = sysAnnouncement.getUserIds();
			String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
			String anntId = sysAnnouncement.getId();
			Date refDate = new Date();
			for(int i=0;i<userIds.length;i++) {
				SysAnnouncementSend announcementSend = new SysAnnouncementSend();
				announcementSend.setAnntId(anntId);
				announcementSend.setUserId(userIds[i]);
				announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
				announcementSend.setReadTime(refDate);
				sysAnnouncementSendMapper.insert(announcementSend);
			}
		}
	}

	/**
	 * 编辑消息信息
	 */
	@Transactional
	@Override
	public boolean upDateAnnouncement(SysAnnouncement sysAnnouncement) {
		// 1.更新系统信息表数据
		sysAnnouncementMapper.updateById(sysAnnouncement);
		if(sysAnnouncement.getMsgType().equals(CommonConstant.MSG_TYPE_USER)) {
			// 2.补充新的通知用户数据
			String userId = sysAnnouncement.getUserIds();
			String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
			String anntId = sysAnnouncement.getId();
			Date refDate = new Date();
			for(int i=0;i<userIds.length;i++) {
				LambdaQueryWrapper<SysAnnouncementSend> queryWrapper = new LambdaQueryWrapper<SysAnnouncementSend>();
				queryWrapper.eq(SysAnnouncementSend::getAnntId, anntId);
				queryWrapper.eq(SysAnnouncementSend::getUserId, userIds[i]);
				List<SysAnnouncementSend> announcementSends=sysAnnouncementSendMapper.selectList(queryWrapper);
				if(announcementSends.size()<=0) {
					SysAnnouncementSend announcementSend = new SysAnnouncementSend();
					announcementSend.setAnntId(anntId);
					announcementSend.setUserId(userIds[i]);
					announcementSend.setReadFlag(CommonConstant.NO_READ_FLAG);
					announcementSend.setReadTime(refDate);
					sysAnnouncementSendMapper.insert(announcementSend);
				}
			}
			// 3. 删除多余通知用户数据
			Collection<String> delUserIds = Arrays.asList(userIds);
			LambdaQueryWrapper<SysAnnouncementSend> queryWrapper = new LambdaQueryWrapper<SysAnnouncementSend>();
			queryWrapper.notIn(SysAnnouncementSend::getUserId, delUserIds);
			queryWrapper.eq(SysAnnouncementSend::getAnntId, anntId);
			sysAnnouncementSendMapper.delete(queryWrapper);
		}
		return true;
	}

	// 流程执行完成保存消息通知
	@Override
	public void saveSysAnnouncement(String title, String msgContent) {
		SysAnnouncement announcement = new SysAnnouncement();
		announcement.setTitile(title);
		announcement.setMsgContent(msgContent);
		announcement.setSender("共享平台");
		announcement.setPriority(CommonConstant.PRIORITY_L);
		announcement.setMsgType(CommonConstant.MSG_TYPE_ALL);
		announcement.setSendStatus(CommonConstant.HAS_SEND);
		announcement.setSendTime(new Date());
		announcement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0));
		sysAnnouncementMapper.insert(announcement);
	}

	@Override
	public Page<SysAnnouncement> querySysCementPageByUserId(Page<SysAnnouncement> page, String userId,String msgCategory) {
		 return page.setRecords(sysAnnouncementMapper.querySysCementListByUserId(page, userId, msgCategory));
	}

	@Override
	public void sendMiddlePrioritySysMsg(String userIds, String title, String msg) {
		if (Strings.isEmpty(userIds)) {
			throw new RuntimeException(title + "，用户id为空！");
		}
		SysAnnouncement sysAnnouncement = new SysAnnouncement();
		// 消息类型为用户消息：给指定用户发消息
		sysAnnouncement.setMsgType(CommonConstant.MSG_TYPE_USER);
		// 接收消息的用户ids 如：id1,id2,id3,...
		// 用户id去重
		userIds = distinctUserIds(userIds);
		sysAnnouncement.setUserIds(userIds);
		Date now = new Date();
		sysAnnouncement.setStartTime(now);
		sysAnnouncement.setSendTime(now);
		sysAnnouncement.setTitile(title);
		sysAnnouncement.setSender("admin");
		sysAnnouncement.setMsgContent(msg);
		sysAnnouncement.setDelFlag(String.valueOf(CommonConstant.DEL_FLAG_0));
		// 优先级为中级
		sysAnnouncement.setPriority(CommonConstant.PRIORITY_M);
		// 发布状态为已发布
		sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_1);
		saveAnnouncement(sysAnnouncement);
	}

	/**
	 * 用户id去重
	 *
	 * @param userIds 可能重复的用户ids
	 * @return 无重复用户ids   例如：id1,id2,id3,
	 */
	private String distinctUserIds(String userIds) {
		if (!userIds.contains(",")) {
			return userIds;
		}
		String[] idArr = userIds.split(",");
		Set<String> uniqueIdSet = new HashSet<>(Arrays.asList(idArr));
		uniqueIdSet.remove("");
		// 注意：此处最后一个id后需要拼接一个字符，因为saveAnnouncement()方法中直接去掉了最后一个字符
		return Strings.join(uniqueIdSet, ',') + ",";
	}

}
